<?php

/*
 * This file is part of the docplus package.
 * (c) Batanayi Matuku <batanayi@docplus.co.za>
 * 
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Create a new admin user.
 *
 * @package    docplus
 * @subpackage task
 * @author     Batanayi Matuku <batanayi@docplus.co.za>
 * @version    SVN: $Id: sfGuardCreateAdminUserTask.class.php
 */
class sfGuardCreateAdminUserTask extends sfBaseTask
{
  /**
   * @see sfTask
   */
  protected function configure()
  {
    $this->addArguments(array(
      new sfCommandArgument('email', sfCommandArgument::REQUIRED, 'The email address'),
      new sfCommandArgument('password', sfCommandArgument::REQUIRED, 'The password'),
      new sfCommandArgument('first_name', sfCommandArgument::REQUIRED, 'The first name'),
      new sfCommandArgument('last_name', sfCommandArgument::REQUIRED, 'The last name'),
      new sfCommandArgument('gender', sfCommandArgument::REQUIRED, 'The gender'),
      new sfCommandArgument('language', sfCommandArgument::REQUIRED, 'The language'),
    ));

    $this->addOptions(array(
      new sfCommandOption('is-super-admin', null, sfCommandOption::PARAMETER_NONE, 'Whether the user is a super admin', null),
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', null),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
    ));

    $this->namespace = 'guard';
    $this->name = 'create-user';
    $this->briefDescription = 'Creates an admin user';

    $this->detailedDescription = <<<EOF
The [guard:create-user|INFO] task creates a user:

  [./symfony guard:create-user mail@example.com password Batanayi Matuku Male English|INFO]
EOF;
  }

  /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
    $databaseManager = new sfDatabaseManager($this->configuration);
    
    // check the existance of the specified language
    $language = LanguageTable::getInstance()->findOneByName($arguments['language']);
    if (!$language)
    {
      throw new sfCommandException(sprintf('Language "%s" does not exist.', $arguments['language']));
    }

    $user = new GfUser();
    $user->setEmail($arguments['email']);
    $user->setPassword($arguments['password']);
    $user->setFirstName($arguments['first_name']);
    $user->setLastName($arguments['last_name']);
    $user->setIsActive(true);
    $user->setIsSuperAdmin($options['is-super-admin']);
    $user->setType('Admin');
    $user->save();
    
    $admin = new Admin();
    $admin->setUser($user);
    $admin->setGender($arguments['gender']);
    $admin->setLanguage($language);
    $admin->save();

    $this->logSection('guard', sprintf('Created user "%s"', $arguments['email']));
  }
}